package com.atgouwu.mall.common.utils;

import io.jsonwebtoken.*;
import org.apache.commons.lang3.StringUtils;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;

/**
 * jwt规则生成token工具类
 */
public class JwtUtils {
    private static long tokenExpiration = 24 * 60 * 60 * 1000; //token过期时间
    private static String tokenSignKey = "A1t2g3uigu123456"; //密钥

    //创建jwt
    public static String createToken(Long userId, String userName) {
        String token = Jwts.builder()
                .setHeaderParam("type", "JWT")
                .setHeaderParam("alg", "HS256") //头信息(不需改)
                .setSubject("SRB-USER") //自定义分类名
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration)) //过期时间
                .claim("userId", userId) //主体信息
                .claim("userName", userName)
                .signWith(SignatureAlgorithm.HS512, getKeyInstance()) //加密方式
                .compressWith(CompressionCodecs.GZIP)
                .compact();
        return token;
    }

    //加密算法
    private static Key getKeyInstance() {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        byte[] bytes = DatatypeConverter.parseBase64Binary(tokenSignKey);
        return new SecretKeySpec(bytes, signatureAlgorithm.getJcaName());
    }

    /**
     * 判断token是否有效
     *
     * @param token
     * @return
     */
    public static boolean checkToken(String token) {
        if (StringUtils.isEmpty(token)) {
            return false;
        }
        try {
            Jwts.parser().setSigningKey(getKeyInstance()).parseClaimsJws(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    //从jwt中获取userId
    public static Long getUserId(String token) {
        Claims claims = getClaims(token);
        Integer userId = (Integer) claims.get("userId");
        return userId.longValue();
    }

    //从jwt中获取userName
    public static String getUserName(String token) {
        Claims claims = getClaims(token);
        return (String) claims.get("userName");
    }

    public static void removeToken(String token) {
        //jwttoken无需删除，客户端扔掉即可。
    }

    /**
     * 校验token并返回Claims
     *
     * @param token
     * @return
     */
    private static Claims getClaims(String token) {
        if (StringUtils.isEmpty(token)) {
            //LOGIN_AUTH_ERROR(-211, "未登录"),
            //throw new BusinessException(ResponseEnum.LOGIN_AUTH_ERROR);
            return null;
        }
        try {
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(getKeyInstance()).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            return claims;
        } catch (Exception e) {
            //throw new BusinessException(ResponseEnum.LOGIN_AUTH_ERROR);
            return null;
        }
    }
}